package com.ruoyi.service.jpjs.progressplan.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.domain.jpjs.common.progressplan.*;
import com.ruoyi.mapper.jpjs.progressplan.ProgressplanMapper;
import com.ruoyi.service.jpjs.progressplan.ProgressplanService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author C.fw
 * @explain 进度计划业务层处理
 * @since 2020/8/15 15:43
 */
@Service
public
class ProgressplanImpl implements ProgressplanService {

    @Resource
    private ProgressplanMapper progressplanMapper;

    @Override
    public List<Progressplan> selectProgressList(Map<String, Object> map) {
        return progressplanMapper.selectProgressList(map);
    }

    @Override
    public int addProgress(Progressplan progressplan) {
        return progressplanMapper.addProgress(progressplan);
    }

    @Override
    public Map<String, Object> selectProgressById(Map<String, Object> map) {
        return progressplanMapper.selectProgressById(map);
    }

    @Override
    public int updateProgressById(Progressplan progressplan) {
        return progressplanMapper.updateProgressById(progressplan);
    }

    @Override
    public int deleteProgressById(String progressArr) {
        String[] progressId = Convert.toStrArray(progressArr);
        return progressplanMapper.deleteProgressById(progressId);
    }

    @Override
    public List<ProgressplanDetail> selectDetailListByProgressId(Map<String, Object> map) {
        return progressplanMapper.selectDetailListByProgressId(map);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addProgressDetail(ProgressplanDetailParam progressplanDetailParam) {
        Progressplan progressplan = new Progressplan();
        progressplan.setProgressId(Integer.valueOf(progressplanDetailParam.getProgressId()));
        progressplan.setActualStartTime(progressplanDetailParam.getActualStartTime());
        progressplan.setActualEndTime(progressplanDetailParam.getActualEndTime());
        progressplanMapper.updateProgressById(progressplan);
        return progressplanMapper.addProgressDetail(progressplanDetailParam);
    }

    @Override
    public List<ProgressplanRemark> selectRemarksByProgressId(Map<String, Object> map) {
        return progressplanMapper.selectRemarksByProgressId(map);
    }


    @Override
    public boolean checkNodeUnique(Progressplan progressplan) {
        // Step1 工程公司、项目名称、楼栋号、节点名称查询
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", progressplan.getCompanyId());
        map.put("programId", progressplan.getProgramId());
        map.put("buildingNumber", progressplan.getBuildingNumber());
        map.put("node", progressplan.getNode());
        List<Progressplan> list = progressplanMapper.checkUnique(map);
        if (StringUtils.isNotEmpty(list)) {
            return true;
        }
        return false;
    }

    @Override
    public List<Progressplan> loopFormatData(List<Progressplan> list) {
        if (StringUtils.isNotEmpty(list)) {
            for (Progressplan progressplan : list) {
                // 设置计划用时、实际用时
                if (StringUtils.isNotEmpty(progressplan.getActualStartTime()) && StringUtils.isNotEmpty(progressplan.getActualEndTime())) {
                    long actualDay = DateUtils.getDaySub(progressplan.getActualStartTime(), progressplan.getActualEndTime());
                    progressplan.setActualNeedTime(String.valueOf(actualDay + 1));
                }

                if (StringUtils.isNotEmpty(progressplan.getPlanStartTime()) && StringUtils.isNotEmpty(progressplan.getPlanEndTime())) {
                    long planDay = DateUtils.getDaySub(progressplan.getPlanStartTime(), progressplan.getPlanEndTime());
                    progressplan.setPlanNeedTime(String.valueOf(planDay + 1));
                }

                // 设置预警信号
                if (StringUtils.isNotEmpty(progressplan.getProgressDetail())) {
                    if (progressplan.getIsMainPath().equals("是")) {
                        if (progressplan.getProgressDetail().contains("滞后")) {
                            int num = Integer.parseInt(StringUtils.extractNum(progressplan.getProgressDetail()));
                            if (num >= 1 && num <= 7) {
                                progressplan.setThreshold("blue");
                            }
                            if (num >= 8 && num <= 14) {
                                progressplan.setThreshold("yellow");
                            }
                            if (num > 14) {
                                progressplan.setThreshold("red");
                            }
                        }
                    }
                } else {
                    progressplan.setProgressDetail("-");
                }

                // 设置进度情况(状态:未完成 + 进度情况:提前 => 未到考核节点 )
                if(progressplan.getStatus().equals("未完成") && progressplan.getProgressDetail().contains("提前")){
                    progressplan.setProgressDetail("未到考核节点");
                }

            }
            return list;
        } else {
            return list;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleEdit(Progressplan progressplan) {

        // Step1 唯一性校验:工程公司、项目名称、楼栋号、节点名称
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", progressplan.getCompanyId());
        map.put("programId", progressplan.getProgramId());
        map.put("buildingNumber", progressplan.getBuildingNumber());
        map.put("node", progressplan.getNode());
        map.put("progressId", progressplan.getProgressId());
        List<Progressplan> list = progressplanMapper.checkUnique(map);
        if (StringUtils.isNotEmpty(list)) {
            return true;
        }

        // Step2 数据准备:计划完成时间变动最新更新进度情况(1.最新进度存在 2.最新进度不存在)
        String interval = "";
        if (!(progressplan.getPlanEndTime().equals(progressplan.getPlanEndTimeOld()))) {
            Map<String, Object> resultMap = progressplanMapper.selectProgressById(map);
            if (StringUtils.isNotEmpty(resultMap) && resultMap.containsKey("actualEndTime")) {
                System.out.println(resultMap.get("actualEndTime"));
                if (resultMap.get("actualEndTime") != null) {
                    // 更新进度情况(实际完成时间-计划完成时间)
                    long intervalDays = DateUtils.getDaySub(progressplan.getPlanEndTime(), resultMap.get("actualEndTime").toString());
                    if (intervalDays > 0) {
                        interval = "滞后" + intervalDays + "天";
                    }
                    if (intervalDays == 0) {
                        interval = "正常";
                    }
                    if (intervalDays < 0) {
                        interval = "提前" + Math.abs(intervalDays) + "天";
                    }
                    ProgressplanDetail progressplanDetail = new ProgressplanDetail();
                    progressplanDetail.setProgressDetail(interval);
                    progressplanDetail.setProgressId(String.valueOf(progressplan.getProgressId()));
                    // 根据id根据更新进度情况
                    progressplanMapper.updateProgressDetailById(progressplanDetail);
                }
            }
        }

        // Step3 业务保证:同一工程公司、项目名称、楼栋号下总楼层及批次统一
        progressplanMapper.updateProgress(progressplan);
        return false;
    }


    @Override
    public boolean handleDataForSave(ProgressplanDetailParam progressplanDetailParam) {

        // Step1 校验新增内容之前是否存在“已完成”,若存在不允许添加
        Map<String, Object> map = new HashMap<>();
        map.put("progressId", progressplanDetailParam.getProgressId());
        List<ProgressplanDetail> list = progressplanMapper.selectDetailListByProgressId(map);
        // 完成之后可更新为已完成,不可更新为未完成
        if (StringUtils.isNotEmpty(list)) {
            if (progressplanDetailParam.getStatus().equals("1") && list.get(0).getStatus().equals("完成")) {
                return true;
            }
        }

        // Step2 添加备注详情
        List<ProgressplanRemark> remarkList = new ArrayList<>();
        List<ProgressplanDetail> lists = progressplanDetailParam.getProgressplanDetail();
        if (StringUtils.isNotEmpty(lists)) {
            for (ProgressplanDetail progressplanDetail : lists) {
                if (StringUtils.isNotEmpty(progressplanDetail.getRemark())) {
                    ProgressplanRemark progressplanRemark = new ProgressplanRemark();
                    progressplanRemark.setProgressId(progressplanDetailParam.getProgressId());
                    progressplanRemark.setReasonType(progressplanDetail.getReasonType());
                    progressplanRemark.setRemark(progressplanDetail.getRemark());
                    remarkList.add(progressplanRemark);
                }
            }
            // 根据进度计划ID,清空进度详情表
            if (StringUtils.isNotEmpty(remarkList)) {
                progressplanMapper.deleteRemarksProgressId(map);
                progressplanMapper.insertRemarksBatches(remarkList);
            }
        }
        return false;
    }

    @Override
    public int addProgressImg(Progressplan progressplan) {
        return progressplanMapper.addProgressImg(progressplan);
    }

    @Override
    public Progressplan selectImg(Map<String, Object> map) {
        return progressplanMapper.selectImg(map);
    }

    @Override
    public Boolean deleteFilePathById(Integer progressId) {
        Map<String, Object> map = new HashMap<>();
        map.put("progressId", progressId);
        List<ProgressplanDetail> excellenctdetail = progressplanMapper.selectDetailListByProgressId(map);
        return FileUtils.deleteFile(excellenctdetail.get(0).getPhysicalPath());
    }

    @Override
    public int updatePathById(Integer progressId) {
        return progressplanMapper.updatePathById(progressId);
    }

    @Override
    public List<ProgressplanRemark> readyForAddView(Progressplan progressplan) {
        // Step1 进度情况数据准备
        // Case1 未完成 进度情况=当前时间-计划完成时间(当前时间大:滞后 当前时间小:提前 当前时间正好:正常)
        // Case2 完成 进度情况= 实际完成时间-计划完成时间(页面处理)

        // 判断完成状态是 完成还是未完成
        Map<String, Object> map = new HashMap<>();
        map.put("progressId", progressplan.getProgressId());
        List<ProgressplanDetail> list = progressplanMapper.selectDetailListByProgressId(map);

        if(StringUtils.isNotEmpty(list) && list.get(0).getStatus().equals("完成")){
            long intervalDays = DateUtils.getDaySub(list.get(0).getPlanEndTime(), list.get(0).getActualEndTime());
            String interval = null;
            if (intervalDays > 0) {
                interval = "滞后" + intervalDays + "天";
            }
            if (intervalDays == 0) {
                interval = "正常";
            }
            if (intervalDays < 0) {
                interval = "提前" + Math.abs(intervalDays) + "天";
            }
            progressplan.setIntervalDays(interval);
        }else{
            long intervalDays = DateUtils.getDaySub(progressplan.getPlanEndTime(), new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            String interval = null;
            if (intervalDays > 0) {
                interval = "滞后" + intervalDays + "天";
            }
            if (intervalDays == 0) {
                interval = "正常";
            }
            if (intervalDays < 0) {
                interval = "提前" + Math.abs(intervalDays) + "天";
            }
            progressplan.setIntervalDays(interval);
        }

        // Step2 实际开始时间、完成状态、影像数据准备用于回显
        if (StringUtils.isNotEmpty(list)) {
            progressplan.setActualStartTime(list.get(0).getActualStartTime());
            progressplan.setStatus(list.get(0).getStatus());
            progressplan.setVirtualPath(list.get(0).getVirtualPath());
            progressplan.setActualEndTime(list.get(0).getActualEndTime());
        }

        // Step3 获取详情描述列表
        return progressplanMapper.selectRemarksByProgressId(map);
    }

    @Override
    public List<Progressplan> queryProgramList() {
        return progressplanMapper.queryProgramList();
    }

    @Override
    public List<Progressplan> queryProjectGroupByProgram() {
        return progressplanMapper.queryProjectGroupByProgram();
    }

    @Override
    public List<Progressplan> queryActualFinishRate(Progressplan progressplan) {
        return progressplanMapper.queryActualFinishRate(progressplan);
    }

    @Override
    public int insertStatisticBatches(List<Progressplan> list) {
        return progressplanMapper.insertStatisticBatches(list);
    }

    @Override
    public int deleteStatisticByProgramId(Progressplan progressplan) {
        return progressplanMapper.deleteStatisticByProgramId(progressplan);
    }

    @Override
    public List<Progressplan> queryStatisticList(Progressplan progressplan) {
        return progressplanMapper.queryStatisticList(progressplan);
    }

    @Override
    public List<Progressplan> queryPlanFinishRate(Map<String, Object> map) {
        return progressplanMapper.queryPlanFinishRate(map);
    }

    @Override
    public List<Progressplan> queryActualRate(Map<String, Object> map) {
        return progressplanMapper.queryActualRate(map);
    }

    @Override
    public List<Progressplan> queryDynamicRate(Map<String, Object> map) {
        return progressplanMapper.queryDynamicRate(map);
    }

    @Override
    public int updateStatusByProgramId(Progressplan progressplan) {
        return progressplanMapper.updateStatusByProgramId(progressplan);
    }


    @Override
    public List<ProgressplanStatistic> queryStatisticListExport(Map<String, Object> map) {
        return progressplanMapper.queryStatisticListExport(map);
    }
}
